package com.distribute.application.utils;
import java.util.HashMap;
import java.util.Map;




import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayFundTransToaccountTransferRequest;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.distribute.framework.core.web.helper.Utils;
import com.google.gson.Gson;
/**
 * 支付宝账号向用户转账工具类（单例）
 * @author Administrator
 *
 */
public class AlipyToUser {
	
		//关联配置文件
		private static String gateway=Utils.config("alipay.pay.gatewayUrl");//支付宝网关
		private static String appid=Utils.config("alipay.pay.appid");//阿里公共账户的id
		private static String private_key=Utils.config("alipay.pay.appPrivateKey");//私钥
		private static String input_charset="UTF-8";//字段类型
		private static String ali_public_key=Utils.config("alipay.pay.alipayPublicKey");//公钥
		private static AlipayClient alipayClient;
		private static AlipyToUser instance=new AlipyToUser();
		public AlipyToUser(){
			alipayClient=new DefaultAlipayClient(gateway, appid, private_key, "json",input_charset,ali_public_key,"RSA2");
		}
		public static AlipyToUser getInstance(){
			return instance;
		}
		/**
		 * 支付宝向用户转账
		 * @param bizNo  逻辑单号
		 * @param amount 转账金额 "1.21"单位元
		 * @param account 支付宝账号
		 * @param userName 支付宝真实姓名
		 * @return
		 */
		public Map<String,String> alipay2User(String bizNo,String amount,String account,String userName){
			System.out.println("bizNo"+bizNo);
			System.out.println("amount"+amount);
			System.out.println("account"+account);
			System.out.println("userName"+userName);
			Map<String,String> resultMap=new HashMap<String,String>();
			AlipayVo vo = new AlipayVo();
			vo.setOut_biz_no(bizNo);
			vo.setPayee_type("ALIPAY_LOGONID");
			vo.setAmount(amount);
			vo.setPayee_account(account);
			vo.setPayer_show_name(userName);
			vo.setPayee_real_name(userName);
		    vo.setRemark("支付宝转账");
			 String json = new Gson().toJson(vo);
			// 设置请求参数
			AlipayFundTransToaccountTransferRequest alipayRequest = new AlipayFundTransToaccountTransferRequest();
			 alipayRequest.setBizContent(json);
			 AlipayFundTransToaccountTransferResponse response=null;
			try {
				response = alipayClient.execute(alipayRequest);
				System.out.println(JSON.toJSONString(response));
				if("10000".equals(response.getCode())){
					resultMap.put("success", "true");
					resultMap.put("des", "转账成功");
				}else{
					resultMap.put("success", "false");
					resultMap.put("des", response.getSubMsg());
				}
			} catch (AlipayApiException e) {
				e.printStackTrace();
				resultMap.put("success", "false");
				resultMap.put("des", "转账失败！");
			}
			return resultMap;
		}
	}